/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import io.renren.common.exception.RRException;
import io.renren.common.utils.WebUtil;
import io.renren.modules.app.annotation.Login;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        String token = WebUtil.getTokenFromRequest(request);
        if (StrUtil.isBlank(token)) {
            throw new RRException("token不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        if (WebUtil.isTokenExpired(token)) {
            throw new RRException("token失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        JWT jwt = JWT.of(token);
        Long userId = (Long) jwt.getPayload(JWT.SUBJECT);
        WebUtil.setLoginUserId(userId);

        return true;
    }
}
